package com.mall.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.mall.context.BaseContext;
import com.mall.domain.dto.ReviewDTO;
import com.mall.domain.po.Review;
import com.mall.domain.po.User;
import com.mall.domain.vo.ReviewVO;
import com.mall.mapper.ReviewMapper;
import com.mall.mapper.UserMapper;
import com.mall.service.ReviewService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @description: 评论服务实现类
 * @author 勾新杰
 * @version 1.0
 * @date 2024/11/27 20:05
 */
@Service
@RequiredArgsConstructor
public class ReviewServiceImpl implements ReviewService {

    private final ReviewMapper reviewMapper;

    private final UserMapper userMapper;

    /**
     * 添加评论
     *
     * @param reviewDTO 评论信息
     */
    @Override
    public void addReview(ReviewDTO reviewDTO) {
        // 1. 构建评论对象
        Review review = Review.builder()
                .userId(BaseContext.getCurrentId())
                .createTime(LocalDateTime.now())
                .build();
        // 2. 将传输对象中的数据复制到实体对象中
        BeanUtil.copyProperties(reviewDTO, review);
        // 3. 插入数据库
        reviewMapper.insert(review);
    }

    /**
     * 获取评论列表
     * @param itemId 商品id
     * @return 评论列表
     */
    @Override
    public List<ReviewVO> list(Long itemId) {
        // 1. 获取评论列表
        List<Review> reviewList = reviewMapper.listByItemId(itemId);
        // 2. 复制属性
        List<ReviewVO> reviewVOS = BeanUtil.copyToList(reviewList, ReviewVO.class);
        // 3. 获取用户信息
        for (ReviewVO reviewVO : reviewVOS) {
            User user = userMapper.getUserById(reviewVO.getUserId());
            reviewVO.setUsername(user.getUsername());
        }
        // 4. 返回结果
        return reviewVOS;
    }

    /**
     * 根据id获取评论
     *
     * @param id 评论id
     * @return 评论
     */
    @Override
    public ReviewVO getById(Long id) {
        // 1. 根据id获取评论
        Review review = reviewMapper.getById(id);
        // 2. 复制属性
        ReviewVO reviewVO = BeanUtil.copyProperties(review, ReviewVO.class);
        // 3. 获取用户信息
        User user = userMapper.getUserById(review.getUserId());
        reviewVO.setUsername(user.getUsername());
        // 4. 返回结果
        return reviewVO;
    }

    /**
     * 根据id删除评论
     *
     * @param id 评论id
     */
    @Override
    public void deleteById(Long id) {
        reviewMapper.deleteById(id);
    }
}
